package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zx
 * @date 2021/11/27 14:22
 */
@Service
@Slf4j
public class ApBehaviorEntryServiceImpl  implements ApBehaviorEntryService {


    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查询行为实体
     * @param userId  用户id
     * @param equipmentId  设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {

        //1. 判断userId是否为空
        if(userId != null){

            //1.1不为空 使用userId查询 行为实体 (refId = 用户id     type = 用户类型  )
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId)
                    .and("type").is(ApBehaviorEntry.Type.USER.getCode())), ApBehaviorEntry.class);
            if(apBehaviorEntry == null){

                //1.2 不存在基于userId创建实体数据
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }
            log.info("查询行为实体成功");
            return apBehaviorEntry;
        }

        log.info("userId为空");

        //2. 判断设备id是否为空   不为空 使用设备id查询
        if(equipmentId != null){

            //2.1不为空 使用设备id查询  行为实体 (refId = 设备id   type = 设备类型)
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(equipmentId)
                    .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())), ApBehaviorEntry.class);

            if(behaviorEntry == null){

                //2.2 不存在基于设备id创建实体数据
                behaviorEntry = new ApBehaviorEntry();

                behaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                behaviorEntry.setRefId(equipmentId);
                behaviorEntry.setCreatedTime(new Date());

                mongoTemplate.save(behaviorEntry);
            }

            log.info("查询行为实体成功");
            return behaviorEntry;
        }

        log.info("equipmentId为空");

        return null;

    }

}

